﻿using System.Collections.Generic;
using System.Linq;
using DataAccess.Entities;
using NHibernate;
using NHibernate.Criterion;

namespace DataAccess.Repositories
{
    public class InterestRepository : IRepository<Interest>
    {
        #region IRepository<Interest> Members

        void IRepository<Interest>.Save(Interest entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(entity);
                    transaction.Commit();
                }
            }
        }

        void IRepository<Interest>.Update(Interest entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Update(entity);
                    transaction.Commit();
                }
            }
        }

        void IRepository<Interest>.Delete(int id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(id);
                    transaction.Commit();
                }
            }
        }

        Interest IRepository<Interest>.GetById(int id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.CreateCriteria<Interest>().Add(Restrictions.Eq("Id", id)).UniqueResult<Interest>();
        }

        IList<Interest> IRepository<Interest>.GetAll()
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.CreateCriteria<Interest>().List<Interest>();
        }

        IList<Interest> IRepository<Interest>.Find(string searchText, int maxResults)
        {
            IList<Interest> interests;
            using (ISession session = NHibernateHelper.OpenSession())
                interests = session.CreateCriteria<Interest>().List<Interest>();

            var result = from n in interests
                         where n.Name.Contains(searchText)
                         orderby n.Name
                         select n;

            return result.Take(maxResults).ToList();
        }

        #endregion
    }
}